<?php
require_once(ROOT . LIBRARY .'/fields/common.inc');

class fields_file extends fields_common
{

   /**
    * Normalize Value
    *
    * @param string $value
    * @param string $lang
    */
   public function normalizeValue($value, $lang = null)
   {
      $this->value = unserialize($value);
      
      return $this->value;
   }


   /**
    * Get HTML code for File fields
    *
    * @param object $data
    * @return string
    */
   public function getFieldHTML($data)
   {
      $html   = '';
      $value = is_object($data) ? $data->{$this->alias}(null) : NULL;

      if($this->translate)
      {
         # TODO: implement multilanguage files support
      } else
      {
         if(empty($value))
         {
            $html .= '<input type="file" name="f['. $this->alias .']';
            if(!empty($this->fieldset)) $html .= '['. (!empty($data->id) ? $data->id : $this->fieldset) .']';
            $html .= '" />';

            $upload_dir_content = getDirList(ROOT . UPLOADS);
            $upload_dir_content = $upload_dir_content['file'];
            if(!empty($upload_dir_content))
            {
               $i = array_search('.htaccess', $upload_dir_content);
               if($i !== FALSE) unset($upload_dir_content[$i]);
            }
            if(!empty($upload_dir_content))
            {
               $html .= '<br />'. gettext::translate('meccano','or') .':<br />';
               $html .= '<select name="f[' . $this->alias . ']';
               if(!empty($this->fieldset)) $html .= '['. (!empty($data->id) ? $data->id : $this->fieldset) .']';
               $html .= '">';
               $html .= '<option value=""></option>';
               foreach ($upload_dir_content AS $uploaded_file)
               {
                  $html .= '<option value="' . $uploaded_file . '">' . $uploaded_file . '</option>';
               }
               $html .= '</select><br />';
               $html .= '<span class="notice">'. gettext::translate('meccano', 'upload_files_note') .'</span>';

            }
         } else
         {
            $html .= '<input type="hidden" name="f['. $this->alias .']';
            if(!empty($this->fieldset)) $html .= '['. (!empty($data->id) ? $data->id : $this->fieldset) .']';
            $html .= '" />';
            $html .= $value['filename'] .' ['. RoundSizeBites($value['filesize']) .']';
         }
      }

      return $html;
   }


   public function validateInput($value, $objectData = NULL)
   {
      // DELETE IMAGE
      if($value == 'delete' && property_exists($this, 'value'))
      {
         if(is_array($this->value))
         {
            if(!empty($this->value['src']) && file_exists(ROOT . $this->value['src']))
            {
               unlink(ROOT . $this->value['src']);
            }
         }
      }
      
      $new_value = NULL;
      $destination_dir = FILES . '/' . ceil($objectData->cat / 25);
      if(!is_dir(ROOT . $destination_dir))
      {
         mkdir(ROOT . $destination_dir);
      }
      
      if(is_array($value) && !empty($value['uploaded']))
      {
         # process as uploaded file
         if (!empty($value['name']) && !empty($value['type']) && !empty($value['tmp_name']) && !empty($value['size']) && empty($value['error']))
         {  
            $file_name = uploadfile($value['name'], ROOT . $destination_dir, $value['tmp_name']);

            // TODO: подумать про антивирусную защиту
            // node belong
            $new_value['src'] = $destination_dir . '/' . $file_name;
            $new_value['filename'] = $value['name'];
            $new_value['filesize'] = $value['size'];
            $new_value['mime'] = $value['type'];
            $new_value['ext'] = strtolower(substr(strrchr($file_name, "."), 1));
         }
      } else
      {
         # process as pre-uploaded file stored in UPLOADS directory
         if(!empty($value) && $value != 'delete' && file_exists(ROOT . UPLOADS . '/'. stripslashes(basename($value))))
         {
            $safe_file_name = ClearFileName($value);

            $new_value = array();
            $new_value['filename'] = $value;
            $new_value['filesize'] = filesize(ROOT . UPLOADS .'/'. stripslashes($value));
            $new_value['src']      = $destination_dir .'/'. MoveFile(ROOT . UPLOADS .'/'. $value, ROOT . $destination_dir .'/'. $safe_file_name);
            $new_value['ext']      = strtolower(substr(strrchr($value, "."), 1));
         }
      }

      $this->value = $new_value;
      
      return $this->value;
   }


   public function saveValue($lang = NULL)
   {
      if(property_exists($this, 'value'))
      {
         return serialize($this->value);
      }

      return '';
   }
}